from flask_restful import Resource
from comment.models.user import User
from flask import current_app, request
from comment.utils.messing_rly import send_message
import random
import json
from comment.utils.limiter import limiter as lmt
from comment.utils.shopping_redis import redis_client
from .import constants
from flask_limiter.util import get_remote_address

class Shopping_User(Resource):
    def get(self):
        current_app.logger.debug('我的测试日志')
        # 这里的代码可能会用到user模型类
        return {'hello': '测试'}

class User_SMS(Resource):
    """
    发送验证码的短信，
    """
    error_message = 'To many requests'
    decorators =[
        # 三个参数： 参数1：限流的速率, 参数2：key_func， 参数3： 如果超出限制之后的提示信息
        lmt.limit(constants.LIMIT_SMS_CODE_BY_MOBILE,
                  key_func=lambda: request.args['phone'],
                  error_message=error_message
                  ),
        lmt.limit(constants.LIMIT_SMS_CODE_BY_IP,
                  key_func=get_remote_address,
                  error_message=error_message
                  )
    ]
    def get(self):
        phone = request.args.get('phone').strip()
        code = random.randint(1000, 9999)
        result = send_message(phone, str(code))  # 返回的是JSON的字符串
        result = json.loads(result)  # 将json变为字典
        # result 往里面添加手机号码
        result['phone'] = phone
        return result



